<?php
defined('IN_IA') or exit('Access Denied');
include __DIR__."/vendor/autoload.php";
//开发模式，生成环境中设置为false
KUYUAN_DEBUG ? error_reporting(E_ALL & ~E_NOTICE) : error_reporting(0);

//验证token，请不要随意更改，更改后前端无法获取数据
define("KUYUAN_TOKEN","shanxikuyuanwangluokeji");

//模块名字，请勿随意修改
define("KUYUAN_MODEL_NAME",'kuyuan_fm');


/**
 * 执行类
 * @param $_className
 * @return mixed
 */
function execClass($_className)
{
    return new $_className();
}

/**
 * 执行方法
 * @param $_class
 * @param $_methodName
 * @return
 */
function execMethod($_class,$_methodName)
{
    return $_class->$_methodName();
}

class kuyuan_fmModuleSite extends WeModuleSite {
    public function doWebApi()
    {
        $this->api();
    }

    public function doMobileApi()
    {
        $this->api();
    }

    private function api()
    {
        global $_GPC;
        if(KUYUAN_DEBUG){
            $this->ajax();
            $this->createRequestParamFile();
        }
        if($_GPC['sign'] != $this->getSign() && count($_FILES) <= 0){
            echo 'sign错误';
            exit;
        }
        if(isset($_GPC['pages']) && !empty($_GPC['pages'])){
            if(!is_file(MODULE_ROOT.'/action/'.ucwords($_GPC['pages']).'.php')){
                exit(ucwords($_GPC['pages']).'.php文件不存在');
            }
            $_action = call_user_func('execClass','App\\'.ucwords($_GPC['pages']));
            if(isset($_GPC['doing']) && !empty($_GPC['doing'])){
                $_methodName = $_GPC['doing'];
            }else{
                $_methodName = 'index';
            }
            if(!method_exists($_action,$_methodName)){
                exit($_methodName.'()方法不存在');
            }
            call_user_func('execMethod',$_action,$_methodName);
        }
    }

    /**
     * 验证sign
     */
    private function getSign()
    {
        $_post_data = $_POST;
        unset($_post_data['sign']);
        $_key_arr = array_keys($_post_data);
        sort($_key_arr,SORT_STRING);
        $_key_str = '';
        foreach($_key_arr as $_v){
            $_key_str .= $_v;
        }
        $_key_str .= KUYUAN_TOKEN;
        return strtoupper(md5($_key_str));
    }


    /**
     * 外部ajaxq请求
     */
    private function ajax()
    {
        header("Access-Control-Allow-Origin:https://192.168.137.2:8080");
        header('Access-Control-Allow-Headers:Authorization');
        header("Access-Control-Allow-Methods: GET, POST");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Headers: Content-Type, X-Requested-With, Cache-Control,Authorization");
    }

    /**
     * 创建请求参数文件，用户ab抗压测试
     */
    private function createRequestParamFile()
    {
        if(count($_POST) <= 0) return;
        $_content = '';
        foreach($_POST as $_k=>$_v){
            $_content .= $_k.'='.$_v.'&';
        }
        file_put_contents(MODULE_ROOT.'/post.text',$_content);
    }


}
